<template>
    <div>
        <el-form ref="ruleFormRef" :model="addressForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item>
                <el-button type="primary" @click="router.back">返回</el-button>
            </el-form-item>
            <el-form-item label="修改" prop="address">
                <el-input v-model="addressForm.address" style="width: 250px;" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    修改
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
import api from '@/api'
import { useRoute } from 'vue-router';
import router from '@/router'

const route = useRoute()

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const addressForm = ref({
    id: route.params.id,
    address: route.params.address
})

const rules = reactive<FormRules>({
    address: [
        {
            required: true,
            message: '地址不能为空',
            trigger: 'change',
        },
    ]
})

const emit = defineEmits(['refresh'])

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.address.editAddress(addressForm.value)
                .then(response => {
                    // 在这里可以处理提交成功后的逻辑
                    ElNotification({
                        title: 'Success',
                        message: response.data.msg,
                        type: 'success',
                        duration: 1500
                    })
                })
                .catch(error => {
                    ElNotification({
                        title: 'Error',
                        message: error.data.msg,
                        type: 'error',
                        duration: 1500
                    })
                    // 在这里可以处理提交失败后的逻辑
                });
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>

<style scoped></style>